from typing import Optional
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from db import get_db, crud, models
from schemas.customer import CustomerPagination
from users.users import verify_token

router = APIRouter(prefix="/customer", tags=["客户管理"])


@router.get("", dependencies=[Depends(verify_token)],
            response_model=CustomerPagination,
            response_model_exclude_none=True)
def get_customer_pagination(page: int, page_size: int, kw: Optional[str] = None, db: Session = Depends(get_db)):
    total, data = crud.Customer.gets(db, page - 1, page_size, kw)
    return CustomerPagination(
        page=page,
        page_size=page_size,
        total=total,
        data=data
    )


@router.get("/stats")
def stats(db: Session = Depends(get_db)):
    data = db.query(
        models.Customer.id,
        models.Customer.nickname,
        models.Customer.created_on,
        models.Customer.gender,
    ).filter_by(status=1).all()

    return [
        {
            "id": item.id,
            "nickname": item.nickname,
            "created_on": item.created_on,
            "gender": item.gender,
        } for item in data
    ]
